﻿using System;
namespace Moonlite.ExtensionApi
{
    public sealed class IconReference : IDisposable, IEquatable<IconReference>
    {
        private readonly IntPtr staticHandle;
        private readonly IntPtr imageList;
        private readonly int index;
        private IntPtr handle;
        private bool disposed;
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        public IntPtr GetHandle()
        {
            if (disposed)
            {
                return IntPtr.Zero;
            }
            if (staticHandle != IntPtr.Zero)
            {
                return staticHandle;
            }
            if (handle != IntPtr.Zero)
            {
                return handle;
            }
            return handle = UnsafeNativeMethods.ImageList_GetIcon(imageList, index, 1);
        }
        void Dispose(bool dispose)
        {
            if (disposed)
            {
                return;
            }
            if (handle != IntPtr.Zero)
            {
                disposed = true;
                UnsafeNativeMethods.DestroyIcon(handle);
            }
        }
        public bool Equals(IconReference other)
        {
            return staticHandle == other.staticHandle &&
                imageList == other.imageList &&
                index == other.index;
        }
        public override bool Equals(object obj)
        {
            return Equals(obj as IconReference);
        }
        public override int GetHashCode()
        {
            return staticHandle.GetHashCode() ^ imageList.GetHashCode() ^ index.GetHashCode();
        }
        public IconReference(IntPtr imageList, int index)
        {
            this.imageList = imageList;
            this.index = index;
        }
        public IconReference(IntPtr handle)
        {
            staticHandle = handle;
        }
        ~IconReference()
        {
            Dispose(false);
        }
    }
}
